// TODO, 授权手机号兼容企业微信。
// 原本是按钮点击调用，企业微信可以接口唤起
// 我们上线的演示号整个这个组件功能就废弃了，因为演示号没有获取手机号的权限
// 问题，变成，如何获取判断当前是否是第三方应用，是的话，不执行相关业务。
// 1. 监听isShow变量变化
// 2. 获取当前环境，
// 3. 企业微信环境，把isShow置为false
const app = getApp();
const { getOpenID, getPhoneNumber } = require('../../utils/ws/wsxcx-opendata-sdk');
const { qyWXLogin } = require('../../utils/ws/ws-wxwork');

Component({
  externalClasses: ['button-class'],
  properties: {
    needEncryptedData: {
      type: Boolean,
      value: false,
    },
    showCancel: {
      type: Boolean,
      value: true,
    },
    isShow: {
      type: Boolean,
      value: false,
      observer: function (newVal, oldVal) {
        newVal && app.isWXWork && this.setData({
          isShow: false,
        });

        // TODO, 企业微信环境，且需要isShow/授权手机号，使用接口唤起。
        newVal && app.isWXWork && this._getWXWorkMobile();
      },
    },
    isBtn: {
      type: Boolean,
      value: false,
    },
    moduleName: {
      type: String,
      value: app.modules,
    },
    url: {
      type: String,
      value: 'auth/session/phoneinfo',
    },
  },

  data: {
    platform: 'android',
    isWXWork: app.isWXWork,
  },

  attached() {
    wx.getSystemInfo({
      success: res => {
        res && res.platform !== 'android' && this.setData({ platform: res.platform });
      },
    });

    wx.getStorageSync('needAuthMobileOnPageLoad') !== false && this.getConfig().then((res) => {
      res && this.setData({
        isShow: true,
      });
    });
  },

  // observers 基础库2.6.1开始支持，比properties性能优。
  watch: {
    'isShow': function(isShow) {
      this.data.isWXWork && this.setData({
        isShow: false,
      });
    },
  },

  methods: {
    getConfig() {
      return new Promise((resolve) => {
        getOpenID({ mode: 1 }).then(() => {
          app.util.request({
            url: 'auth/session/copyright',
            method: 'get',
            success: res => {
              let response = res.data.data || '';
              res.statusCode === 200 && response && resolve(!!Number(response.mobilestate));
              // 已绑定过或后台关闭开关，都不再重复请求接口。
              !Number(response.mobilestate) && wx.setStorageSync('needAuthMobileOnPageLoad', false);
            },
          });
        });
      });
    },

    _bindphone(e) {
      this.setData({
        isShow: false,
      }, function() {
        wx.showLoading();
      });

      let { moduleName, url, needEncryptedData } = this.data;
      const success = (res) => {
        if (Number(res.data.errno) === 0 && res.data.data) {
          let eventData = { mobile: res.data.data.mobile };
          needEncryptedData && (eventData.encryptedData = e.detail.encryptedData);
          needEncryptedData && (eventData.iv = e.detail.iv);

          this.triggerEvent('getUserMobile', eventData);
          wx.setStorageSync('needAuthMobileOnPageLoad', false);
        }
      };

      const shopSuccess = (res) => {
        if (res.code === 0) {
          let userInfor = wx.getStorageSync('user_info') || {};
          userInfor.mobile = res.data.mobile;
          wx.setStorageSync('user_info', userInfor);  // 商城缓存
          this.triggerEvent('getUserMobile', { mobile: res.data.mobile });
          wx.hideLoading();
        }
      };

      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        moduleName === 'ws_micro_shop' && this.shopRequest(e, shopSuccess);
        moduleName === 'ws_micro_shop' || this.commonRequest(e, url, success);
      } else {
        this.triggerEvent('cancelAuthMobile', { mobile: '' });
        setTimeout(() => { wx.hideLoading()}, 500)
      }
    },

    // 商城专用
    shopRequest(e, success) {
      app.ws_micro_shoprequest({
        url: app.api.passport.bind_mobile,
        data: {
          encrypted_data: e.detail.encryptedData,
          iv: e.detail.iv,
        },
        method: 'POST',
        success,
        fail: function() {
          wx.hideLoading();
        },
      });
    },

    // 其他模块使用
    commonRequest(e, url, success) {
      let reqData = {
        url,
        method: 'post',
        cachetime: 60,
        detail: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        },
      };

      getOpenID({ mode: 1 }).then(openID => {
        getPhoneNumber({ ...reqData, openid: openID })
          .then((res) => {
            success && typeof success === 'function' && success(res);
            wx.hideLoading();
          })
          .catch(() => wx.hideLoading());
      });
    },

    _togglePop() {
      this.setData({ isShow: false });
      this.triggerEvent('cancelAuthMobile', { mobile: '' });
    },

    _getWXWorkMobile() {

      // 不写获取企业微信员工手机号的公共接口了，就这里单独处理。
      qyWXLogin({
        success: function () {
          wx.qy.getMobile({
            success: function(res) {
              console.log(res.encryptedData);
              console.log(res.iv);

              return; // 接口OK就放开。
              app.util.request({
                url: 'xxx',
                cachetime: 60,
                // TODO, 企业微信成员手机号接口可能会换
                detail: {
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                },
                success: function (res) {
                  // TODO，接口数据结构再议
                  if (res.code === 0) {
                    this.triggerEvent('getUserMobile', { mobile: res.data.mobile });
                  }
                },
              });
            },
          });
        },
      });
    },
  },
});
